import os, stat
import urllib.request
import requests
import threading
import re
import xlrd

from PIL import Image
import requests
import random


def ua():
    ua_pool = [

        "Mozilla/5.0 (Windows NT 6.2;en-US) AppleWebKit/537.32.36 (KHTML, live Gecko) Chrome/59.0.3047.101 Safari/537.32",

        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36",

        "Mozilla/5.0 (iPhone; CPU iPhone OS 14_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.5(0x18000528) NetType/4G Language/zh_CN",

        "Mozilla/5.0 (Linux; Android 11; M2012K11AC Build/RKQ1.200826.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/77.0.3865.120 MQQBrowser/6.2 TBS/045613 Mobile Safari/537.36 MMWEBID/7803 MicroMessenger/8.0.3.1880(0x2800033D) Process/tools WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64",

        "Mozilla/5.0 (Linux; Android 9; Mi Note 3 Build/PKQ1.181007.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/77.0.3865.120 MQQBrowser/6.2 TBS/045609 Mobile Safari/537.36 MMWEBID/4799 MicroMessenger/8.0.2.1860(0x2800023D) Process/tools WeChat/arm64 Weixin NetType/4G Language/zh_CN ABI/arm64",

        "Mozilla/5.0 (iPhone; CPU iPhone OS 14_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.5(0x18000528) NetType/4G Language/zh_CN",

        "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)",

        "Mozilla/5.0 (Linux; Android 11; V1824A Build/RP1A.200720.012; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/77.0.3865.120 MQQBrowser/6.2 TBS/045611 Mobile Safari/537.36 MMWEBID/8305 MicroMessenger/8.0.2.1860(0x2800023D) Process/tools WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64",

        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36",

        "Mozilla/5.0 (iPhone; CPU iPhone OS 14_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.3(0x1800032c) NetType/WIFI Language/zh_CN",

        "Mozilla/5.0 (Linux; U; Android 10; zh-cn; MI 9 Build/QKQ1.190825.002) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.141 Mobile Safari/537.36 XiaoMi/MiuiBrowser/13.3.12",
    ]
    return ua_pool[random.randint(1, 10)]


def login():
    login_url = 'http://sw.eccang.com/default/index/login'
    headers = {
        # "Accept": "application/json, text/javascript, */*; q=0.01",
        "User-Agent": "{}".format(ua()),
        "Referer": "http://sw.eccang.com/default/index/logout?company_code=sw"
    }
    body = {
        "userName": "jinhuaitao",
        "userPass": "jht834719#",
        "companyCode": ""
    }
    try:
        res = requests.post(url=login_url, headers=headers, data=body)
        cookies = res.cookies.items()
        print(cookies)
        cookie = ''
        for name, value in cookies:
            cookie += '{0}={1};'.format(name, value)
        print('UM_distinctid=17c15b16b7275-02b55430879ff9-2343360-1fa400-17c15b16b7376d;' + cookie)
        return cookie
    except Exception as err:
        print('获取cookie失败：\n{0}'.format(err))


headers = {
    'Cookie': '{}'.format(login()),
    "User-Agent": "{}".format(ua()),

}

skuall = []
tu_all = []


def res():
    images1 = input('填写sku相对应无图片excel表格')
    g = open(r'D:\images\{}.xlsx'.format(images1), 'w', encoding='utf-8')
    for da in list3:
        famar = {
            'product_status': '1',
            'sale_status': '',
            'type': 'sku_precision',
            'code': '{}'.format(da),
            'product_name_type': '1',
            'product_name': '',
            'supplier_code': '',
            'product_source': '0',
            'product_weight': '',
            'decr_check': '',
            'is_qc': '',
            'contain_non_liquid_cosmetics': '',
            'contain_special_goods': '',
            'product_is_public': '',
            'product_is_combination': '',
            'images_ok': '',
            'default_buy_warehouse_id': '',
            'sp_supplier_sku': '',
            'currency_code': '',
            'opration_type': '',
            'prl_id': '',
            'prt_id': '',
            'category[]': '',
            'opration_time_type': '1',
            'dateFrom': '',
            'dateTo': '',
            'decpriceFrom': '',
            'decpriceTo': '',
            'oversea_type_cn': '',
            'person_type': '',
            'person': '',
            'pv_id': '',
            'longest': '',
            'volume': '',
            'sum_side': '',
            'searchType': '1',
            'diy_form_id': '',
            'diy_form_val': '',
            'product_package': '',
            'brand_id': '',
            'default_warehouse_id': '',
            'user_organization[]': '',
            'sku_len_start': '',
            'sku_len_end': '',
            'logistic_attribute': '',
            'product_color': '',
            'order_by': '',
        }
        try:
            url = 'http://sw.eccang.com/product/develop/list/page/1/pageSize/10'
            res1 = requests.post(url, headers=headers, data=famar, verify=False).json()
            # print(res1)
            for i in res1["data"]:

                if i["product_img"] != '/images/base/noimg.jpg':  # and i["product_img"][-3:] != 'png'
                    print(i["product_barcode"], i["product_img"])
                    img_url = i["product_img"]
                    file_path = 'D:/img'
                    file_name = i["product_barcode"]
                    tu_all.append(file_name)

                    # 是否有这个路径
                    if not os.path.exists(file_path):
                        # 创建路径
                        os.makedirs(file_path)
                        # 获得图片后缀
                    file_suffix = os.path.splitext(img_url)[1]

                    # print(file_suffix)
                    # 拼接图片名（包含路径）
                    filename = '{}{}{}{}'.format(file_path, os.sep, file_name, file_suffix)
                    # print(filename)
                    # 下载图片，并保存到文件夹中
                    urllib.request.urlretrieve(img_url, filename=filename)
                    skuall.append(i["product_barcode"])
                else:
                    g.write('{}\n'.format(da))
        except Exception as gl:
            url = 'http://sw.eccang.com/product/develop/list/page/1/pageSize/10'
            res1 = requests.post(url, headers=headers, data=famar, verify=False).json()
            # print(res1)
            for i in res1["data"]:

                if i["product_img"] != '/images/base/noimg.jpg':  # and i["product_img"][-3:] != 'png'
                    print(i["product_barcode"], i["product_img"])
                    img_url = i["product_img"]
                    file_path = 'D:/img'
                    file_name = i["product_barcode"]
                    tu_all.append(file_name)

                    # 是否有这个路径
                    if not os.path.exists(file_path):
                        # 创建路径
                        os.makedirs(file_path)
                        # 获得图片后缀
                    file_suffix = os.path.splitext(img_url)[1]

                    # print(file_suffix)
                    # 拼接图片名（包含路径）
                    filename = '{}{}{}{}'.format(file_path, os.sep, file_name, file_suffix)
                    # print(filename)
                    # 下载图片，并保存到文件夹中
                    urllib.request.urlretrieve(img_url, filename=filename)
                    skuall.append(i["product_barcode"])
                else:
                    g.write('{}\n'.format(da))


import xlsxwriter


def all():
    images = input('填写最后生成的图片与sku相对应的excel表格')
    workbook = xlsxwriter.Workbook(r'D:\images\{}.xlsx'.format(images))
    worksheet = workbook.add_worksheet()
    # print(tu_all)

    for i in range(1, len(list3) + 1):

        list01 = []
        try:
            try:
                path = os.path.join(os.getcwd(), r'D:\img\{}.jpg'.format(list3[i - 1]))
                img = Image.open(path)
                img_size = img.size
                # print('size', img_size)
                list01.append(img_size)
            except Exception as g:
                path = os.path.join(os.getcwd(), r'D:\img\{}.png'.format(list3[i - 1]))
                img = Image.open(path)
                img_size = img.size
                # print('size', img_size)
                list01.append(img_size)
            image_width = list01[0][0] + 0.0
            image_height = list01[0][1] + 0.0
            cell_width = 64.0
            cell_height = 40.0
            x_scale = (cell_width - 5) * 1.0 / image_width
            y_scale = (cell_height + 10) * 1.0 / image_height

            # 加宽第一列使文本更清晰。
            worksheet.set_column('A:A', 10)
            # 加宽图片列

            worksheet.set_column(1, 45)
            worksheet.set_default_row(45)

            worksheet.insert_image('A{}'.format(i), r'D:\img\{}.jpg'.format(list3[i - 1]),
                                   {'x_offset': 2, 'y_offset': 2, 'x_scale': x_scale, 'y_scale': y_scale,
                                    'positioning': 1})

            worksheet.insert_image('A{}'.format(i), r'D:\img\{}.png'.format(list3[i - 1]),
                                   {'x_offset': 2, 'y_offset': 2, 'x_scale': x_scale, 'y_scale': y_scale,
                                    'positioning': 1})
            worksheet.write('B{}'.format(i), '{}'.format(list3[i - 1]))
        except Exception as g:
            worksheet.write('B{}'.format(i), '{}'.format(list3[i - 1]))

    workbook.close()


list3 = []


def guolv():
    weizhi = input('填写sku所在excel名称')  # 从excel获取sku
    num = input('填写sku所在excel中的最大行数')
    workbook = xlrd.open_workbook(r'D:/sku/{}.xlsx'.format(weizhi))
    sheet = workbook.sheet_by_name('Sheet1')
    for i in range(0, int(num)):
        names00 = sheet.cell(i, 0)
        name00 = re.findall("text:'(.*?)'", str(names00))
        if name00 == []:
            name00 = 'none'
        else:
            name00 = re.findall("text:'(.*?)'", str(names00))[0]
        # print(name00)
        list3.append(name00)
    return list3


guolv()
res()
all()
